#!/usr/bin/env python

'''
M190

Copyright (C) 2019  Phillip A Carter

This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
'''

import sys
import time

from subprocess import Popen,PIPE

materialnum = int(float(sys.argv[1]))

def get_material():
    return int(Popen(['halcmd getp plasmac_run.material-change-number'], stdout=PIPE, shell=True).communicate()[0].strip())

def get_change():
    return int(Popen(['halcmd getp plasmac_run.material-change'], stdout=PIPE, shell=True).communicate()[0].strip())

def set_material(material):
    Popen(['halcmd setp plasmac_run.material-change-number %d' %(material)], shell=True)

def set_change(value):
    Popen(['halcmd setp plasmac_run.material-change %d' %(value)], shell=True)

set_change(0)
if materialnum != get_material():
    set_material(materialnum)
    start = time.time()
    while get_change() == 0:
        if time.time() > start + 3:
            print("T{}: timeout waiting for material-change".format(materialnum))
            break
    if get_change() < 0:
        print("Material #{}: does not exist".format(materialnum))
set_change(0)
exit()
